<?php
/**
 * // +----------------------------------------------------------------------
 * //            -------------------------
 * //           /   / ------------------\  \
 * //                                          \  \
 * //                                           /  /
 * //          /  /  ------------------- /  /
 * //        /  /  ----------------------
 * //      /  /
 * //      \  \
 * //        \  \  ------------------ /  /
 * //          \  \--------------------/
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2016 Sage  All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Author: Sage
 * // +----------------------------------------------------------------------
 *
 */

/**
 * Created by PhpStorm.
 * User: Sage
 * Date: 2017/12/7
 * Time: 15:35
 */
namespace KysbsUtils\Service;
use OSS\OssClient;
use KysbsUtils\Config;

class OssService {
    private static $OssClient;
    private static $compressSize=819200;
    private static $bucketType=[
        'image'=>'xuetu-images',
        'file'=>'xuetu-files'
    ];
    private static $compress=true;
    private static $error='no error';

    /**
     * 上传图片
     * @param $file_path
     * @param $oss_name
     */
    function uploadImage($file_path,$oss_name=false){
        if(!file_exists($file_path)){
            self::setErrorMsg('上传文件不存在');
            return false;
        }
        $bucket=self::bucket('image');
        //压缩图片
        if(self::$compress){
            $r=self::compress($file_path);
            if(false !== stripos($r,'error')){
                self::setErrorMsg($r);
                return false;
            }
            $file_path=$r;
        }
        if($oss_name===false){
            $oss_name=md5(microtime().rand());
        }
        $url=self::doUpload($bucket,$file_path,$oss_name);
        return $url;
    }

    /**
     * 上传文件
     * @param $file_path
     * @param $oss_name
     */
    function uploadFile($file_path,$oss_name=false){
        if(!file_exists($file_path)){
            self::setErrorMsg('上传文件不存在');
            return false;
        }
        $bucket=self::bucket('file');
        if($oss_name===false){
            $oss_name=md5(microtime());
        }
        $url=self::doUpload($bucket,$file_path,$oss_name);
        if(false !== stripos($url,'error')){
            self::setErrorMsg($url);
            return false;
        }
        return $url;
    }

    /**
     * 上传
     * @param $bucket
     * @param $file_path
     * @param $oss_name
     *
     * @return array|string
     */
    private function doUpload($bucket,$file_path,$oss_name){
        if(!file_exists($file_path)){
            self::setErrorMsg('上传文件不存在,101');
            return false;
        }
        $domain=self::getCname($bucket);
        $OssClient=self::drive();

        $oss_res=$OssClient->uploadFile($bucket, $oss_name, $file_path);
        $oss_url=$domain.'/'.$oss_name;
        if($domain==''){
            $oss_url=$oss_res['info']['url'];
        }
        unlink($file_path);
        return $oss_url;
    }

    /**
     * 获取自定义域名
     * @param $bucket
     *
     * @return array
     */
    private function getCname($bucket){
        $OssClient=self::drive();
        $cnameConfig =$OssClient->getBucketCname($bucket);
        $oss_res=$cnameConfig->getCnames();
        $cname=$oss_res[0]['Domain'];
        if($cname!=''){
            $cname='http://'.$cname;
        }
        return $cname;
    }

    /**
     * 图片压缩
     * @param $mv_file
     *
     * @return string
     */
    private function compress($mv_file){
        $cop_file=Config::TMP_STORAGE.DIRECTORY_SEPARATOR.md5(microtime().random_int(1,100000));
        //        $r=$this->imageCompress($mv_file,$cop_file,M_IMG_COMPRESS_W_MAX,M_IMG_COMPRESS_H_MAX,false);
        $Image=new ImageService();
        $r=$Image->CompressByImgSize($mv_file,$cop_file,self::$compressSize);
        if(false !== stripos($r,'error')){
            unlink($cop_file);
            unlink($mv_file);
            self::setErrorMsg('error图片压缩失败,'.$r);
            return 'error图片压缩失败,'.$r;
        }
        return $r;
    }

    /**
     * 生成OSS类
     * @return OssClient
     */
    function drive(){
        $Client=self::$OssClient;
        if(empty($Client)){
            $accessKeyId = Config::OSS_KEY_ID;
            $accessKeySecret = Config::OSS_KEY_SECRET;
            $endpoint = Config::OSS_ENDPOINT;
            $Client=new OssClient( $accessKeyId, $accessKeySecret, $endpoint);
            $Client->setTimeout(60);
            self::$OssClient=$Client;
        }
        return $Client;
    }

    /**
     * 获取或设置bucket
     * @param string $type,bucket的类型
     * @param bool   $value,传值则为设置对应类型的bucket为$value值
     *
     * @return mixed，返回对应的bucket类型的bucket
     */
    function bucket($type='image',$value=false){
        if($value===false)
            return self::$bucketType[$type];
        else
            self::$bucketType[$type]=$value;
        return self::$bucketType[$type];
    }

    /**
     * 图片样式
     * @param string $type
     */
    function style($url,$style=false){
        if($style!=false)
            $url.='?x-oss-process=style/'.$style;
        return $url;
    }

    /**
     * 错误信息
     * @param $error
     */
    function setErrorMsg($error){
        self::$error=$error;
    }

    /**
     * 获取错误信息
     */
    function getErrorMsg(){
        return self::$error;
    }
}